import moment from 'moment';
/**
 * 为localstorage添加过期时间
 */
class ExpireStorage {
  constructor() {
    const expireKeysString = window.localStorage.getItem('expire_keys');
    let expireKeys = [];
    try {
      expireKeys = JSON.parse(expireKeysString);
      // eslint-disable-next-line
    } catch (error) {}

    this.expireKeys = Array.isArray(expireKeys) ? expireKeys : [];
  }

  setItem(
    key,
    originData = '',
    expire = moment()
      .add('days', 1)
      .valueOf()
  ) {
    const dataObject = {
      data: originData,
      expire
    };
    let dataString = '';
    try {
      // eslint-disable-next-line
      dataString = JSON.stringify(dataObject);
      // eslint-disable-next-line
    } catch (error) {
      dataString = '{}';
    }
    if (this.expireKeys.indexOf(key) === -1) {
      this.expireKeys.push(key);
      window.localStorage.setItem('expire_keys', JSON.stringify(this.expireKeys));
    }
    window.localStorage.setItem(key, dataString);
  }

  getItem(key) {
    const dataString = window.localStorage.getItem(key) || '';
    let dataObject;
    try {
      dataObject = JSON.parse(dataString);
    } catch (error) {
      dataObject = {};
    }
    const { expire, data = '' } = dataObject;
    if (!isNaN(Number(expire)) && Number(expire) > Date.now()) {
      return data;
    } else {
      return null;
    }
  }

  removeItem(suffix) {
    this.expireKeys.map(key => {
      if (key.indexOf(suffix) === 0) {
        window.localStorage.removeItem(key);
      }
    });
  }

  clearExpire(suffix = '') {
    this.expireKeys.map(key => {
      if (key.indexOf(suffix) !== 0) {
        return;
      }
      const item = this.getItem(key);
      if (!item) {
        window.localStorage.removeItem(key);
      }
    });
  }
}

export default new ExpireStorage();
